package 高频题;

import java.util.PriorityQueue;

public class 合并K个升序链表_23 {
    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;//空链表直接返回
        PriorityQueue<ListNode> sHeap = new PriorityQueue<ListNode>((a, b) -> a.val - b.val);

        ListNode fake = new ListNode();
        ListNode cur = fake;//保留头结点作为信标
        for (ListNode node : lists) {
            if (node != null) {
                sHeap.add(node);//加入最小堆
            }
        }
        while (!sHeap.isEmpty()) {
            ListNode poll = sHeap.poll();
            cur.next = poll;
            cur = cur.next;

            // 将最小值的下一个节点添加进「集合」（如果有的话）
            if (poll.next != null) {

                sHeap.add(poll.next);//头节点放了，如果头节点还有下一个那就把下一个要放进小顶堆
            }
        }
        return fake.next;
    }
}
